package com.example.blog.dao;

import com.example.blog.pojo.User;
import com.example.blog.util.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BaseDao {
    private QueryRunner queryRunner = new QueryRunner();

    /**
     * 通过该方法来实现数据库的增删改操作
     * @param sql
     * @param args
     * @return 如果返回-1 说明操作失败
     */
    public int update(String sql,Object ...args){

        try {
            Connection connection = JDBCUtil.getConnection();
            return queryRunner.update(connection, sql, args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     *  查询返回一个JavaBean的sql语句
     * @param <T> 返回类的泛型
     * @param type JavaBean的类型
     * @param sql
     * @param args
     * @return
     *
     *      BeanHandler 通过得到的ResultSet结果集，转换为JavaBean对象
     */
    public <T> T queryForOne(Class<T> type, String sql, Object ...args){
        try {
            Connection connection = JDBCUtil.getConnection();
            return queryRunner.query(connection,sql,new BeanHandler<T>(type), args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     *  查询返回一个List集合对象
     * @param type
     * @param sql
     * @param args
     * @param <T>
     * @return
     *
     *      BeanListHandler 通过查询到的结果集，转换为JavaBean对象
     */
    public <T> List<T> queryForList(Class<T> type, String sql,Object ...args){
        try {
            Connection connection =JDBCUtil.getConnection();
            return queryRunner.query(connection,sql,new BeanListHandler<T>(type), args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 对于单个属性的查询
     * @param sql
     * @param args
     * @return
     *          ScalarHandler 处理一行的数据
     */
    public Object queryForSingleValue(String sql, Object ...args){
        try {
            Connection connection = JDBCUtil.getConnection();
            return queryRunner.query(connection,sql,new ScalarHandler(), args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
